"""
Agent增强服务实现

为现有Agent Laboratory系统的Agent添加智能决策能力，包括：
- Professor Agent智能协调功能
- PhD Student Agent个性化学习能力
- ML Engineer Agent实验优化能力
- Agent间智能通信和协作
"""
import json
import asyncio
from typing import List, Dict, Any, Optional, Tuple
from datetime import datetime, timedelta
from dataclasses import dataclass, asdict, field
from collections import defaultdict, Counter
from enum import Enum

from ..models.analysis_models import (
    UserBehavior, UserPreferences, Context, Recommendations
)
from .preference_analysis_service import PreferenceAnalysisService
from .personalized_recommendation_service import PersonalizedRecommendationService
from .interface_adapter_service import InterfaceAdapterService


class AgentRole(Enum):
    """Agent角色枚举"""
    PROFESSOR = "professor"
    PHD_STUDENT = "phd_student"
    ML_ENGINEER = "ml_engineer"
    POSTDOC = "postdoc"
    REVIEWER = "reviewer"


class DecisionType(Enum):
    """决策类型枚举"""
    COORDINATION = "coordination"
    LEARNING_PATH = "learning_path"
    EXPERIMENT_OPTIMIZATION = "experiment_optimization"
    RESOURCE_ALLOCATION = "resource_allocation"
    QUALITY_ASSESSMENT = "quality_assessment"


@dataclass
class AgentDecision:
    """Agent决策"""
    decision_id: str = ""
    agent_role: AgentRole = AgentRole.PHD_STUDENT
    decision_type: DecisionType = DecisionType.LEARNING_PATH
    context: Dict[str, Any] = field(default_factory=dict)
    options: List[Dict[str, Any]] = field(default_factory=list)
    selected_option: Optional[Dict[str, Any]] = None
    confidence: float = 0.0
    reasoning: List[str] = field(default_factory=list)
    timestamp: datetime = field(default_factory=datetime.now)
    outcome: Optional[str] = None


@dataclass
class AgentCapability:
    """Agent能力"""
    capability_id: str = ""
    name: str = ""
    description: str = ""
    agent_roles: List[AgentRole] = field(default_factory=list)
    enhancement_level: float = 0.0  # 0.0-1.0
    usage_count: int = 0
    success_rate: float = 0.0


class AgentEnhancementService:
    """Agent增强服务"""
    
    def __init__(self,
                 preference_service: Optional[PreferenceAnalysisService] = None,
                 recommendation_service: Optional[PersonalizedRecommendationService] = None,
                 interface_service: Optional[InterfaceAdapterService] = None):
        self.preference_service = preference_service or PreferenceAnalysisService()
        self.recommendation_service = recommendation_service or PersonalizedRecommendationService()
        self.interface_service = interface_service or InterfaceAdapterService()
        
        # Agent决策历史
        self.agent_decisions: Dict[str, List[AgentDecision]] = defaultdict(list)
        self.agent_capabilities: Dict[AgentRole, List[AgentCapability]] = defaultdict(list)
        
        # Agent协作状态
        self.collaboration_sessions: Dict[str, Dict[str, Any]] = {}
        self.agent_performance_metrics: Dict[str, Dict[str, float]] = defaultdict(dict)
        
        # 初始化Agent能力
        self._initialize_agent_capabilities()
    
    def _initialize_agent_capabilities(self):
        """初始化Agent能力"""
        # Professor Agent能力
        professor_capabilities = [
            AgentCapability(
                capability_id="intelligent_coordination",
                name="智能协调",
                description="基于项目状态和团队能力进行智能任务协调",
                agent_roles=[AgentRole.PROFESSOR],
                enhancement_level=0.8
            ),
            AgentCapability(
                capability_id="quality_oversight",
                name="质量监督",
                description="实时监控研究质量并提供改进建议",
                agent_roles=[AgentRole.PROFESSOR],
                enhancement_level=0.9
            ),
            AgentCapability(
                capability_id="strategic_planning",
                name="战略规划",
                description="制定长期研究战略和里程碑规划",
                agent_roles=[AgentRole.PROFESSOR],
                enhancement_level=0.7
            )
        ]
        
        # PhD Student Agent能力
        phd_capabilities = [
            AgentCapability(
                capability_id="personalized_learning",
                name="个性化学习",
                description="基于学习风格和进度的个性化学习路径",
                agent_roles=[AgentRole.PHD_STUDENT],
                enhancement_level=0.8
            ),
            AgentCapability(
                capability_id="adaptive_research",
                name="自适应研究",
                description="根据研究进展自动调整研究方法和重点",
                agent_roles=[AgentRole.PHD_STUDENT],
                enhancement_level=0.7
            ),
            AgentCapability(
                capability_id="intelligent_literature_analysis",
                name="智能文献分析",
                description="深度分析文献并识别研究机会",
                agent_roles=[AgentRole.PHD_STUDENT],
                enhancement_level=0.9
            )
        ]
        
        # ML Engineer Agent能力
        ml_capabilities = [
            AgentCapability(
                capability_id="experiment_optimization",
                name="实验优化",
                description="自动优化实验参数和配置",
                agent_roles=[AgentRole.ML_ENGINEER],
                enhancement_level=0.9
            ),
            AgentCapability(
                capability_id="resource_management",
                name="资源管理",
                description="智能分配和管理计算资源",
                agent_roles=[AgentRole.ML_ENGINEER],
                enhancement_level=0.8
            ),
            AgentCapability(
                capability_id="performance_monitoring",
                name="性能监控",
                description="实时监控实验性能并预警异常",
                agent_roles=[AgentRole.ML_ENGINEER],
                enhancement_level=0.8
            )
        ]
        
        # 存储能力
        for capabilities in [professor_capabilities, phd_capabilities, ml_capabilities]:
            for capability in capabilities:
                for role in capability.agent_roles:
                    self.agent_capabilities[role].append(capability)
    
    async def enhance_professor_coordination(self, agent_id: str, 
                                           project_context: Dict[str, Any],
                                           team_status: Dict[str, Any]) -> Dict[str, Any]:
        """增强Professor Agent的智能协调功能"""
        try:
            # 分析项目状态
            project_analysis = await self._analyze_project_status(project_context)
            
            # 分析团队能力和负载
            team_analysis = await self._analyze_team_capacity(team_status)
            
            # 生成协调决策
            coordination_decision = await self._generate_coordination_decision(
                agent_id, project_analysis, team_analysis
            )
            
            # 记录决策
            self.agent_decisions[agent_id].append(coordination_decision)
            
            # 生成协调建议
            coordination_recommendations = {
                'task_assignments': coordination_decision.selected_option.get('task_assignments', []),
                'priority_adjustments': coordination_decision.selected_option.get('priority_adjustments', []),
                'resource_allocations': coordination_decision.selected_option.get('resource_allocations', {}),
                'timeline_adjustments': coordination_decision.selected_option.get('timeline_adjustments', []),
                'quality_checkpoints': coordination_decision.selected_option.get('quality_checkpoints', []),
                'reasoning': coordination_decision.reasoning,
                'confidence': coordination_decision.confidence
            }
            
            return coordination_recommendations
            
        except Exception as e:
            print(f"Professor协调增强失败: {e}")
            return {'error': '协调增强失败'}
    
    async def enhance_phd_personalized_learning(self, agent_id: str,
                                              learning_context: Dict[str, Any],
                                              progress_data: Dict[str, Any]) -> Dict[str, Any]:
        """增强PhD Student Agent的个性化学习能力"""
        try:
            # 分析学习偏好
            if agent_id not in self.preference_service.user_preferences:
                await self.preference_service.update_preference_model(agent_id)
            
            user_preferences = self.preference_service.user_preferences.get(agent_id)
            
            # 分析学习进度
            progress_analysis = await self._analyze_learning_progress(progress_data)
            
            # 生成个性化学习路径
            learning_decision = await self._generate_learning_decision(
                agent_id, user_preferences, learning_context, progress_analysis
            )
            
            # 记录决策
            self.agent_decisions[agent_id].append(learning_decision)
            
            # 生成学习建议
            learning_recommendations = {
                'learning_path': learning_decision.selected_option.get('learning_path', []),
                'study_materials': learning_decision.selected_option.get('study_materials', []),
                'practice_exercises': learning_decision.selected_option.get('practice_exercises', []),
                'difficulty_adjustment': learning_decision.selected_option.get('difficulty_adjustment', 'maintain'),
                'focus_areas': learning_decision.selected_option.get('focus_areas', []),
                'estimated_time': learning_decision.selected_option.get('estimated_time', {}),
                'reasoning': learning_decision.reasoning,
                'confidence': learning_decision.confidence
            }
            
            return learning_recommendations
            
        except Exception as e:
            print(f"PhD个性化学习增强失败: {e}")
            return {'error': '个性化学习增强失败'}
    
    async def enhance_ml_experiment_optimization(self, agent_id: str,
                                               experiment_context: Dict[str, Any],
                                               performance_data: Dict[str, Any]) -> Dict[str, Any]:
        """增强ML Engineer Agent的实验优化能力"""
        try:
            # 分析实验性能
            performance_analysis = await self._analyze_experiment_performance(performance_data)
            
            # 生成优化决策
            optimization_decision = await self._generate_optimization_decision(
                agent_id, experiment_context, performance_analysis
            )
            
            # 记录决策
            self.agent_decisions[agent_id].append(optimization_decision)
            
            # 生成优化建议
            optimization_recommendations = {
                'parameter_adjustments': optimization_decision.selected_option.get('parameter_adjustments', {}),
                'architecture_changes': optimization_decision.selected_option.get('architecture_changes', []),
                'resource_optimization': optimization_decision.selected_option.get('resource_optimization', {}),
                'training_strategy': optimization_decision.selected_option.get('training_strategy', {}),
                'monitoring_alerts': optimization_decision.selected_option.get('monitoring_alerts', []),
                'reasoning': optimization_decision.reasoning,
                'confidence': optimization_decision.confidence
            }
            
            return optimization_recommendations
            
        except Exception as e:
            print(f"ML实验优化增强失败: {e}")
            return {'error': '实验优化增强失败'}
    
    async def _analyze_project_status(self, project_context: Dict[str, Any]) -> Dict[str, Any]:
        """分析项目状态"""
        analysis = {
            'completion_rate': 0.0,
            'quality_score': 0.0,
            'risk_level': 'low',
            'bottlenecks': [],
            'critical_path': [],
            'resource_utilization': {}
        }
        
        try:
            # 分析完成率
            total_tasks = project_context.get('total_tasks', 1)
            completed_tasks = project_context.get('completed_tasks', 0)
            analysis['completion_rate'] = completed_tasks / total_tasks if total_tasks > 0 else 0
            
            # 分析质量分数
            quality_metrics = project_context.get('quality_metrics', {})
            if quality_metrics:
                analysis['quality_score'] = sum(quality_metrics.values()) / len(quality_metrics)
            
            # 识别瓶颈
            task_durations = project_context.get('task_durations', {})
            if task_durations:
                avg_duration = sum(task_durations.values()) / len(task_durations)
                bottlenecks = [task for task, duration in task_durations.items() 
                             if duration > avg_duration * 1.5]
                analysis['bottlenecks'] = bottlenecks
            
            # 评估风险级别
            if analysis['completion_rate'] < 0.3 and analysis['quality_score'] < 0.6:
                analysis['risk_level'] = 'high'
            elif analysis['completion_rate'] < 0.6 or analysis['quality_score'] < 0.7:
                analysis['risk_level'] = 'medium'
            
        except Exception as e:
            print(f"项目状态分析失败: {e}")
        
        return analysis
    
    async def _analyze_team_capacity(self, team_status: Dict[str, Any]) -> Dict[str, Any]:
        """分析团队能力和负载"""
        analysis = {
            'total_capacity': 0.0,
            'current_utilization': 0.0,
            'skill_distribution': {},
            'workload_balance': 'balanced',
            'available_resources': []
        }
        
        try:
            team_members = team_status.get('members', [])
            
            for member in team_members:
                # 计算总容量
                capacity = member.get('capacity', 1.0)
                analysis['total_capacity'] += capacity
                
                # 计算当前利用率
                current_load = member.get('current_load', 0.0)
                analysis['current_utilization'] += current_load
                
                # 分析技能分布
                skills = member.get('skills', [])
                for skill in skills:
                    if skill not in analysis['skill_distribution']:
                        analysis['skill_distribution'][skill] = 0
                    analysis['skill_distribution'][skill] += 1
                
                # 识别可用资源
                if current_load < capacity * 0.8:  # 80%以下认为有空余
                    analysis['available_resources'].append(member.get('id', ''))
            
            # 计算利用率
            if analysis['total_capacity'] > 0:
                utilization_rate = analysis['current_utilization'] / analysis['total_capacity']
                
                if utilization_rate > 0.9:
                    analysis['workload_balance'] = 'overloaded'
                elif utilization_rate < 0.5:
                    analysis['workload_balance'] = 'underutilized'
        
        except Exception as e:
            print(f"团队能力分析失败: {e}")
        
        return analysis
    
    async def _generate_coordination_decision(self, agent_id: str,
                                            project_analysis: Dict[str, Any],
                                            team_analysis: Dict[str, Any]) -> AgentDecision:
        """生成协调决策"""
        decision = AgentDecision(
            decision_id=f"coord_{agent_id}_{datetime.now().timestamp()}",
            agent_role=AgentRole.PROFESSOR,
            decision_type=DecisionType.COORDINATION,
            context={'project_analysis': project_analysis, 'team_analysis': team_analysis}
        )
        
        try:
            # 生成决策选项
            options = []
            
            # 选项1: 重新分配任务
            if project_analysis['bottlenecks'] and team_analysis['available_resources']:
                options.append({
                    'type': 'task_reallocation',
                    'task_assignments': [
                        {'task': bottleneck, 'assignee': resource}
                        for bottleneck, resource in zip(
                            project_analysis['bottlenecks'][:2],
                            team_analysis['available_resources'][:2]
                        )
                    ],
                    'expected_impact': 0.8
                })
            
            # 选项2: 调整优先级
            if project_analysis['risk_level'] == 'high':
                options.append({
                    'type': 'priority_adjustment',
                    'priority_adjustments': [
                        {'task': 'quality_review', 'new_priority': 'high'},
                        {'task': 'risk_mitigation', 'new_priority': 'critical'}
                    ],
                    'expected_impact': 0.7
                })
            
            # 选项3: 资源重新分配
            if team_analysis['workload_balance'] == 'overloaded':
                options.append({
                    'type': 'resource_reallocation',
                    'resource_allocations': {
                        'additional_time': '20%',
                        'external_support': True,
                        'tool_upgrades': ['automation_tools']
                    },
                    'expected_impact': 0.6
                })
            
            # 选择最佳选项
            if options:
                best_option = max(options, key=lambda x: x.get('expected_impact', 0))
                decision.selected_option = best_option
                decision.confidence = best_option.get('expected_impact', 0.5)
                decision.reasoning = [
                    f"基于项目完成率{project_analysis['completion_rate']:.1%}和质量分数{project_analysis['quality_score']:.2f}",
                    f"团队利用率{team_analysis['current_utilization']/team_analysis['total_capacity']:.1%}",
                    f"选择{best_option['type']}策略以优化项目进展"
                ]
            else:
                decision.selected_option = {'type': 'maintain_status', 'expected_impact': 0.5}
                decision.confidence = 0.5
                decision.reasoning = ["当前项目状态良好，维持现状"]
            
            decision.options = options
            
        except Exception as e:
            print(f"生成协调决策失败: {e}")
            decision.selected_option = {'type': 'error', 'expected_impact': 0.0}
            decision.confidence = 0.0
        
        return decision
    
    async def _analyze_learning_progress(self, progress_data: Dict[str, Any]) -> Dict[str, Any]:
        """分析学习进度"""
        analysis = {
            'completion_rate': 0.0,
            'learning_velocity': 0.0,
            'difficulty_level': 'appropriate',
            'knowledge_gaps': [],
            'strengths': [],
            'recommended_pace': 'maintain'
        }
        
        try:
            # 分析完成率
            total_modules = progress_data.get('total_modules', 1)
            completed_modules = progress_data.get('completed_modules', 0)
            analysis['completion_rate'] = completed_modules / total_modules if total_modules > 0 else 0
            
            # 分析学习速度
            time_spent = progress_data.get('time_spent_hours', 1)
            analysis['learning_velocity'] = completed_modules / time_spent if time_spent > 0 else 0
            
            # 分析测试成绩
            test_scores = progress_data.get('test_scores', [])
            if test_scores:
                avg_score = sum(test_scores) / len(test_scores)
                
                if avg_score < 0.6:
                    analysis['difficulty_level'] = 'too_difficult'
                    analysis['recommended_pace'] = 'slow_down'
                elif avg_score > 0.9:
                    analysis['difficulty_level'] = 'too_easy'
                    analysis['recommended_pace'] = 'speed_up'
            
            # 识别知识空白
            topic_scores = progress_data.get('topic_scores', {})
            for topic, score in topic_scores.items():
                if score < 0.7:
                    analysis['knowledge_gaps'].append(topic)
                elif score > 0.9:
                    analysis['strengths'].append(topic)
        
        except Exception as e:
            print(f"学习进度分析失败: {e}")
        
        return analysis
    
    async def _generate_learning_decision(self, agent_id: str,
                                        user_preferences: Optional[UserPreferences],
                                        learning_context: Dict[str, Any],
                                        progress_analysis: Dict[str, Any]) -> AgentDecision:
        """生成学习决策"""
        decision = AgentDecision(
            decision_id=f"learn_{agent_id}_{datetime.now().timestamp()}",
            agent_role=AgentRole.PHD_STUDENT,
            decision_type=DecisionType.LEARNING_PATH,
            context={'learning_context': learning_context, 'progress_analysis': progress_analysis}
        )
        
        try:
            options = []
            
            # 基于知识空白的学习路径
            if progress_analysis['knowledge_gaps']:
                options.append({
                    'type': 'gap_focused_learning',
                    'learning_path': [
                        {'topic': gap, 'priority': 'high', 'estimated_hours': 4}
                        for gap in progress_analysis['knowledge_gaps'][:3]
                    ],
                    'difficulty_adjustment': 'increase_support',
                    'expected_improvement': 0.8
                })
            
            # 基于学习风格的路径
            if user_preferences and user_preferences.learning_style:
                style_materials = {
                    'visual': ['diagrams', 'videos', 'infographics'],
                    'analytical': ['papers', 'case_studies', 'data_analysis'],
                    'experimental': ['labs', 'projects', 'simulations']
                }
                
                materials = style_materials.get(user_preferences.learning_style, ['mixed_materials'])
                
                options.append({
                    'type': 'style_adapted_learning',
                    'study_materials': materials,
                    'learning_path': [
                        {'topic': 'current_focus', 'materials': materials, 'estimated_hours': 6}
                    ],
                    'expected_improvement': 0.7
                })
            
            # 基于进度的调整
            if progress_analysis['recommended_pace'] != 'maintain':
                pace_adjustment = {
                    'slow_down': {'hours_per_week': 8, 'difficulty': 'reduce'},
                    'speed_up': {'hours_per_week': 15, 'difficulty': 'increase'}
                }
                
                adjustment = pace_adjustment.get(progress_analysis['recommended_pace'], {})
                options.append({
                    'type': 'pace_adjustment',
                    'learning_path': [{'adjustment': adjustment}],
                    'expected_improvement': 0.6
                })
            
            # 选择最佳选项
            if options:
                best_option = max(options, key=lambda x: x.get('expected_improvement', 0))
                decision.selected_option = best_option
                decision.confidence = best_option.get('expected_improvement', 0.5)
                decision.reasoning = [
                    f"基于{progress_analysis['completion_rate']:.1%}的完成率",
                    f"学习速度为{progress_analysis['learning_velocity']:.2f}模块/小时",
                    f"识别到{len(progress_analysis['knowledge_gaps'])}个知识空白",
                    f"推荐{best_option['type']}学习策略"
                ]
            else:
                decision.selected_option = {'type': 'continue_current_path'}
                decision.confidence = 0.6
                decision.reasoning = ["当前学习进展良好，继续现有路径"]
            
            decision.options = options
            
        except Exception as e:
            print(f"生成学习决策失败: {e}")
            decision.selected_option = {'type': 'error'}
            decision.confidence = 0.0
        
        return decision
    
    async def _analyze_experiment_performance(self, performance_data: Dict[str, Any]) -> Dict[str, Any]:
        """分析实验性能"""
        analysis = {
            'current_metrics': {},
            'performance_trend': 'stable',
            'bottlenecks': [],
            'optimization_opportunities': [],
            'resource_efficiency': 0.0
        }
        
        try:
            # 分析当前指标
            metrics = performance_data.get('metrics', {})
            analysis['current_metrics'] = metrics
            
            # 分析性能趋势
            metric_history = performance_data.get('metric_history', [])
            if len(metric_history) >= 3:
                recent_avg = sum(metric_history[-3:]) / 3
                earlier_avg = sum(metric_history[:3]) / 3
                
                if recent_avg > earlier_avg * 1.1:
                    analysis['performance_trend'] = 'improving'
                elif recent_avg < earlier_avg * 0.9:
                    analysis['performance_trend'] = 'declining'
            
            # 识别瓶颈
            resource_usage = performance_data.get('resource_usage', {})
            for resource, usage in resource_usage.items():
                if usage > 0.9:  # 90%以上使用率
                    analysis['bottlenecks'].append(resource)
            
            # 识别优化机会
            if metrics.get('accuracy', 0) < 0.8:
                analysis['optimization_opportunities'].append('improve_model_architecture')
            
            if resource_usage.get('gpu_utilization', 0) < 0.5:
                analysis['optimization_opportunities'].append('increase_batch_size')
            
            # 计算资源效率
            total_resources = sum(resource_usage.values()) if resource_usage else 1
            performance_score = metrics.get('accuracy', 0) * metrics.get('f1_score', 0)
            analysis['resource_efficiency'] = performance_score / total_resources if total_resources > 0 else 0
        
        except Exception as e:
            print(f"实验性能分析失败: {e}")
        
        return analysis
    
    async def _generate_optimization_decision(self, agent_id: str,
                                            experiment_context: Dict[str, Any],
                                            performance_analysis: Dict[str, Any]) -> AgentDecision:
        """生成优化决策"""
        decision = AgentDecision(
            decision_id=f"opt_{agent_id}_{datetime.now().timestamp()}",
            agent_role=AgentRole.ML_ENGINEER,
            decision_type=DecisionType.EXPERIMENT_OPTIMIZATION,
            context={'experiment_context': experiment_context, 'performance_analysis': performance_analysis}
        )
        
        try:
            options = []
            
            # 基于瓶颈的优化
            if performance_analysis['bottlenecks']:
                bottleneck_solutions = {
                    'gpu_memory': {'batch_size': 'reduce', 'model_size': 'optimize'},
                    'cpu': {'num_workers': 'increase', 'preprocessing': 'optimize'},
                    'memory': {'data_loading': 'optimize', 'caching': 'enable'}
                }
                
                for bottleneck in performance_analysis['bottlenecks']:
                    if bottleneck in bottleneck_solutions:
                        options.append({
                            'type': 'bottleneck_resolution',
                            'resource_optimization': bottleneck_solutions[bottleneck],
                            'target_bottleneck': bottleneck,
                            'expected_improvement': 0.7
                        })
            
            # 基于性能趋势的优化
            if performance_analysis['performance_trend'] == 'declining':
                options.append({
                    'type': 'performance_recovery',
                    'parameter_adjustments': {
                        'learning_rate': 'reduce',
                        'regularization': 'increase',
                        'early_stopping': 'enable'
                    },
                    'expected_improvement': 0.6
                })
            
            # 基于优化机会的改进
            for opportunity in performance_analysis['optimization_opportunities']:
                if opportunity == 'improve_model_architecture':
                    options.append({
                        'type': 'architecture_optimization',
                        'architecture_changes': [
                            'add_dropout_layers',
                            'increase_model_depth',
                            'add_batch_normalization'
                        ],
                        'expected_improvement': 0.8
                    })
                elif opportunity == 'increase_batch_size':
                    options.append({
                        'type': 'training_optimization',
                        'training_strategy': {
                            'batch_size': 'increase',
                            'gradient_accumulation': 'enable'
                        },
                        'expected_improvement': 0.5
                    })
            
            # 选择最佳选项
            if options:
                best_option = max(options, key=lambda x: x.get('expected_improvement', 0))
                decision.selected_option = best_option
                decision.confidence = best_option.get('expected_improvement', 0.5)
                decision.reasoning = [
                    f"当前性能趋势: {performance_analysis['performance_trend']}",
                    f"识别到{len(performance_analysis['bottlenecks'])}个瓶颈",
                    f"资源效率: {performance_analysis['resource_efficiency']:.2f}",
                    f"选择{best_option['type']}优化策略"
                ]
            else:
                decision.selected_option = {'type': 'maintain_current_setup'}
                decision.confidence = 0.6
                decision.reasoning = ["当前实验配置已优化，维持现状"]
            
            decision.options = options
            
        except Exception as e:
            print(f"生成优化决策失败: {e}")
            decision.selected_option = {'type': 'error'}
            decision.confidence = 0.0
        
        return decision
    
    async def get_agent_performance_metrics(self, agent_id: str, days: int = 30) -> Dict[str, Any]:
        """获取Agent性能指标"""
        try:
            cutoff_date = datetime.now() - timedelta(days=days)
            
            # 获取决策历史
            recent_decisions = [
                decision for decision in self.agent_decisions.get(agent_id, [])
                if decision.timestamp > cutoff_date
            ]
            
            if not recent_decisions:
                return {'error': '没有足够的决策数据'}
            
            metrics = {
                'agent_id': agent_id,
                'analysis_period_days': days,
                'total_decisions': len(recent_decisions),
                'decision_types': {},
                'average_confidence': 0.0,
                'success_rate': 0.0,
                'decision_quality': {}
            }
            
            # 分析决策类型分布
            decision_type_counts = Counter(d.decision_type.value for d in recent_decisions)
            metrics['decision_types'] = dict(decision_type_counts)
            
            # 计算平均置信度
            confidences = [d.confidence for d in recent_decisions if d.confidence > 0]
            if confidences:
                metrics['average_confidence'] = sum(confidences) / len(confidences)
            
            # 计算成功率（基于有结果的决策）
            decisions_with_outcome = [d for d in recent_decisions if d.outcome]
            if decisions_with_outcome:
                successful_decisions = [d for d in decisions_with_outcome if d.outcome == 'success']
                metrics['success_rate'] = len(successful_decisions) / len(decisions_with_outcome)
            
            # 分析决策质量
            for decision_type in DecisionType:
                type_decisions = [d for d in recent_decisions if d.decision_type == decision_type]
                if type_decisions:
                    avg_confidence = sum(d.confidence for d in type_decisions) / len(type_decisions)
                    metrics['decision_quality'][decision_type.value] = {
                        'count': len(type_decisions),
                        'average_confidence': avg_confidence
                    }
            
            return metrics
            
        except Exception as e:
            print(f"获取Agent性能指标失败: {e}")
            return {'error': 'Agent性能指标获取失败'}
    
    async def export_agent_data(self, agent_id: str) -> Dict[str, Any]:
        """导出Agent数据"""
        try:
            export_data = {
                'agent_id': agent_id,
                'export_date': datetime.now().isoformat(),
                'decisions': [],
                'performance_metrics': {},
                'capabilities': []
            }
            
            # 导出决策历史
            if agent_id in self.agent_decisions:
                export_data['decisions'] = [
                    asdict(decision) for decision in self.agent_decisions[agent_id]
                ]
            
            # 导出性能指标
            if agent_id in self.agent_performance_metrics:
                export_data['performance_metrics'] = self.agent_performance_metrics[agent_id]
            
            # 导出能力信息
            for role, capabilities in self.agent_capabilities.items():
                for capability in capabilities:
                    export_data['capabilities'].append(asdict(capability))
            
            return export_data
            
        except Exception as e:
            print(f"导出Agent数据失败: {e}")
            return {'error': 'Agent数据导出失败'}
    
    async def delete_agent_data(self, agent_id: str) -> bool:
        """删除Agent数据"""
        try:
            if agent_id in self.agent_decisions:
                del self.agent_decisions[agent_id]
            
            if agent_id in self.agent_performance_metrics:
                del self.agent_performance_metrics[agent_id]
            
            # 清理协作会话中的相关数据
            sessions_to_remove = []
            for session_id, session_data in self.collaboration_sessions.items():
                if agent_id in session_data.get('participants', []):
                    sessions_to_remove.append(session_id)
            
            for session_id in sessions_to_remove:
                del self.collaboration_sessions[session_id]
            
            return True
            
        except Exception as e:
            print(f"删除Agent数据失败: {e}")
            return False
    
    async def enhance_ml_experiment_optimization(self, agent_id: str,
                                               experiment_context: Dict[str, Any],
                                               performance_data: Dict[str, Any]) -> Dict[str, Any]:
        """增强ML Engineer Agent的实验优化能力"""
        try:
            # 分析实验性能
            performance_analysis = await self._analyze_experiment_performance(performance_data)
            
            # 分析实验性能
            performance_analysis = await self._analyze_experiment_performance(performance_data)
            
            # 生成优化决策
            optimization_decision = await self._generate_optimization_decision(
                agent_id, experiment_context, performance_analysis, resource_analysis
            )
            
            # 记录决策
            self.agent_decisions[agent_id].append(optimization_decision)
            
            # 生成优化建议
            optimization_recommendations = {
                'parameter_adjustments': optimization_decision.selected_option.get('parameter_adjustments', {}),
                'architecture_changes': optimization_decision.selected_option.get('architecture_changes', []),
                'resource_optimization': optimization_decision.selected_option.get('resource_optimization', {}),
                'training_strategy': optimization_decision.selected_option.get('training_strategy', {}),
                'monitoring_alerts': optimization_decision.selected_option.get('monitoring_alerts', []),
                'expected_improvement': optimization_decision.selected_option.get('expected_improvement', {}),
                'reasoning': optimization_decision.reasoning,
                'confidence': optimization_decision.confidence
            }
            
            return optimization_recommendations
            
        except Exception as e:
            print(f"ML实验优化增强失败: {e}")
            return {'error': '实验优化增强失败'}    

    async def _analyze_project_status(self, project_context: Dict[str, Any]) -> Dict[str, Any]:
        """分析项目状态"""
        analysis = {
            'completion_rate': 0.0,
            'quality_score': 0.0,
            'timeline_status': 'on_track',
            'bottlenecks': [],
            'risks': [],
            'opportunities': []
        }
        
        try:
            # 分析完成率
            total_tasks = project_context.get('total_tasks', 1)
            completed_tasks = project_context.get('completed_tasks', 0)
            analysis['completion_rate'] = completed_tasks / total_tasks
            
            # 分析质量分数
            quality_metrics = project_context.get('quality_metrics', {})
            if quality_metrics:
                analysis['quality_score'] = sum(quality_metrics.values()) / len(quality_metrics)
            
            # 分析时间线状态
            planned_duration = project_context.get('planned_duration_days', 30)
            elapsed_duration = project_context.get('elapsed_duration_days', 0)
            
            if elapsed_duration > planned_duration * 1.1:
                analysis['timeline_status'] = 'delayed'
            elif elapsed_duration < planned_duration * 0.9:
                analysis['timeline_status'] = 'ahead'
            
            # 识别瓶颈
            task_durations = project_context.get('task_durations', {})
            if task_durations:
                avg_duration = sum(task_durations.values()) / len(task_durations)
                for task, duration in task_durations.items():
                    if duration > avg_duration * 1.5:
                        analysis['bottlenecks'].append(task)
            
            # 识别风险
            if analysis['completion_rate'] < 0.5 and elapsed_duration > planned_duration * 0.7:
                analysis['risks'].append('项目进度滞后风险')
            
            if analysis['quality_score'] < 0.7:
                analysis['risks'].append('质量不达标风险')
            
            # 识别机会
            if analysis['timeline_status'] == 'ahead':
                analysis['opportunities'].append('提前完成，可以增加功能或提升质量')
            
        except Exception as e:
            print(f"项目状态分析失败: {e}")
        
        return analysis
    
    async def _analyze_team_capacity(self, team_status: Dict[str, Any]) -> Dict[str, Any]:
        """分析团队能力和负载"""
        analysis = {
            'total_capacity': 0.0,
            'current_load': 0.0,
            'available_capacity': 0.0,
            'skill_distribution': {},
            'workload_balance': 'balanced',
            'recommendations': []
        }
        
        try:
            team_members = team_status.get('team_members', {})
            
            total_capacity = 0.0
            current_load = 0.0
            skill_counts = defaultdict(int)
            
            for member_id, member_info in team_members.items():
                capacity = member_info.get('capacity', 1.0)
                load = member_info.get('current_load', 0.0)
                skills = member_info.get('skills', [])
                
                total_capacity += capacity
                current_load += load
                
                for skill in skills:
                    skill_counts[skill] += 1
            
            analysis['total_capacity'] = total_capacity
            analysis['current_load'] = current_load
            analysis['available_capacity'] = max(0, total_capacity - current_load)
            analysis['skill_distribution'] = dict(skill_counts)
            
            # 分析工作负载平衡
            if total_capacity > 0:
                load_ratio = current_load / total_capacity
                if load_ratio > 0.9:
                    analysis['workload_balance'] = 'overloaded'
                    analysis['recommendations'].append('团队负载过重，需要调整任务分配')
                elif load_ratio < 0.6:
                    analysis['workload_balance'] = 'underutilized'
                    analysis['recommendations'].append('团队负载较轻，可以承担更多任务')
            
            # 分析技能分布
            if len(skill_counts) < 3:
                analysis['recommendations'].append('团队技能多样性不足，建议增加技能培训')
            
        except Exception as e:
            print(f"团队能力分析失败: {e}")
        
        return analysis
    
    async def _generate_coordination_decision(self, agent_id: str,
                                            project_analysis: Dict[str, Any],
                                            team_analysis: Dict[str, Any]) -> AgentDecision:
        """生成协调决策"""
        decision = AgentDecision(
            decision_id=f"coord_{agent_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
            agent_role=AgentRole.PROFESSOR,
            decision_type=DecisionType.COORDINATION,
            context={
                'project_analysis': project_analysis,
                'team_analysis': team_analysis
            }
        )
        
        # 生成协调选项
        options = []
        
        # 选项1: 重新分配任务
        if team_analysis['workload_balance'] == 'overloaded':
            options.append({
                'option_id': 'redistribute_tasks',
                'name': '重新分配任务',
                'task_assignments': ['将高负载成员的任务转移给空闲成员'],
                'priority_adjustments': ['降低非关键任务优先级'],
                'expected_impact': 0.7
            })
        
        # 选项2: 调整项目优先级
        if project_analysis['timeline_status'] == 'delayed':
            options.append({
                'option_id': 'adjust_priorities',
                'name': '调整项目优先级',
                'priority_adjustments': ['专注核心功能，推迟次要功能'],
                'timeline_adjustments': ['延长关键任务时间'],
                'expected_impact': 0.8
            })
        
        # 选项3: 增加质量检查点
        if project_analysis['quality_score'] < 0.7:
            options.append({
                'option_id': 'quality_checkpoints',
                'name': '增加质量检查点',
                'quality_checkpoints': ['每周质量评审', '代码审查强化'],
                'resource_allocations': {'quality_assurance': 0.2},
                'expected_impact': 0.6
            })
        
        # 默认选项: 维持现状
        if not options:
            options.append({
                'option_id': 'maintain_status',
                'name': '维持现状',
                'task_assignments': [],
                'expected_impact': 0.5
            })
        
        decision.options = options
        
        # 选择最佳选项
        best_option = max(options, key=lambda x: x.get('expected_impact', 0))
        decision.selected_option = best_option
        decision.confidence = best_option.get('expected_impact', 0.5)
        
        # 生成推理
        decision.reasoning = [
            f"基于项目完成率{project_analysis['completion_rate']:.1%}和质量分数{project_analysis['quality_score']:.2f}",
            f"团队当前负载状态: {team_analysis['workload_balance']}",
            f"选择方案: {best_option['name']}，预期影响: {best_option['expected_impact']:.1%}"
        ]
        
        return decision
    
    async def _analyze_learning_progress(self, progress_data: Dict[str, Any]) -> Dict[str, Any]:
        """分析学习进度"""
        analysis = {
            'completion_rate': 0.0,
            'learning_velocity': 0.0,
            'difficulty_level': 'appropriate',
            'knowledge_gaps': [],
            'strengths': [],
            'recommendations': []
        }
        
        try:
            # 分析完成率
            total_modules = progress_data.get('total_modules', 1)
            completed_modules = progress_data.get('completed_modules', 0)
            analysis['completion_rate'] = completed_modules / total_modules
            
            # 分析学习速度
            study_days = progress_data.get('study_days', 1)
            analysis['learning_velocity'] = completed_modules / study_days
            
            # 分析难度适应性
            success_rate = progress_data.get('success_rate', 0.5)
            if success_rate > 0.9:
                analysis['difficulty_level'] = 'too_easy'
            elif success_rate < 0.6:
                analysis['difficulty_level'] = 'too_hard'
            
            # 识别知识空白
            weak_areas = progress_data.get('weak_areas', [])
            analysis['knowledge_gaps'] = weak_areas
            
            # 识别优势
            strong_areas = progress_data.get('strong_areas', [])
            analysis['strengths'] = strong_areas
            
            # 生成建议
            if analysis['difficulty_level'] == 'too_easy':
                analysis['recommendations'].append('增加学习难度，引入更具挑战性的内容')
            elif analysis['difficulty_level'] == 'too_hard':
                analysis['recommendations'].append('降低学习难度，加强基础知识巩固')
            
            if analysis['learning_velocity'] < 0.5:
                analysis['recommendations'].append('调整学习节奏，增加练习时间')
            
        except Exception as e:
            print(f"学习进度分析失败: {e}")
        
        return analysis
    
    async def _generate_learning_decision(self, agent_id: str,
                                        user_preferences: Optional[UserPreferences],
                                        learning_context: Dict[str, Any],
                                        progress_analysis: Dict[str, Any]) -> AgentDecision:
        """生成学习决策"""
        decision = AgentDecision(
            decision_id=f"learn_{agent_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}",
            agent_role=AgentRole.PHD_STUDENT,
            decision_type=DecisionType.LEARNING_PATH,
            context={
                'learning_context': learning_context,
                'progress_analysis': progress_analysis,
                'user_preferences': asdict(user_preferences) if user_preferences else {}
            }
        )
        
        # 生成学习选项
        options = []
        
        # 基于学习风格的选项
        if user_preferences and user_preferences.learning_style == 'visual':
            options.append({
                'option_id': 'visual_learning',
                'name': '视觉化学习路径',
                'learning_path': ['图表分析', '可视化工具', '案例研究'],
                'study_materials': ['视频教程', '图解资料', '交互式演示'],
                'expected_effectiveness': 0.8
            })
        elif user_preferences and user_preferences.learning_style == 'analytical':
            options.append({
                'option_id': 'analytical_learning',
                'name': '分析型学习路径',
                'learning_path': ['理论基础', '数学推导', '算法分析'],
                'study_materials': ['学术论文', '技术文档', '数学教材'],
                'expected_effectiveness': 0.9
            })
        
        # 基于进度的选项
        if progress_analysis['difficulty_level'] == 'too_easy':
            options.append({
                'option_id': 'advanced_track',
                'name': '进阶学习轨道',
                'difficulty_adjustment': 'increase',
                'focus_areas': ['高级算法', '前沿研究', '创新方法'],
                'expected_effectiveness': 0.7
            })
        elif progress_analysis['difficulty_level'] == 'too_hard':
            options.append({
                'option_id': 'foundation_track',
                'name': '基础强化轨道',
                'difficulty_adjustment': 'decrease',
                'focus_areas': ['基础概念', '核心原理', '基本技能'],
                'expected_effectiveness': 0.8
            })
        
        # 默认选项
        if not options:
            options.append({
                'option_id': 'standard_track',
                'name': '标准学习轨道',
                'learning_path': ['循序渐进', '理论实践结合'],
                'expected_effectiveness': 0.6
            })
        
        decision.options = options
        
        # 选择最佳选项
        best_option = max(options, key=lambda x: x.get('expected_effectiveness', 0))
        decision.selected_option = best_option
        decision.confidence = best_option.get('expected_effectiveness', 0.6)
        
        # 生成推理
        decision.reasoning = [
            f"基于学习进度完成率{progress_analysis['completion_rate']:.1%}",
            f"当前难度水平: {progress_analysis['difficulty_level']}",
            f"学习风格: {user_preferences.learning_style if user_preferences else '未知'}",
            f"选择方案: {best_option['name']}"
        ]
        
        return decision
    
    async def _analyze_experiment_performance(self, performance_data: Dict[str, Any]) -> Dict[str, Any]:
        """分析实验性能"""
